import React, {useCallback, Component} from 'react';
import {View, Text, Switch} from 'react-native-ui-lib';
import {ActivityIndicator, TouchableOpacity, Alert, AccessibilityInfo} from 'react-native';
import {SearchInput, Button, Colors} from 'react-native-ui-lib';
import {TestCase, TestSuite} from '@rnoh/testerino';
import {Keyboard} from 'react-native';

type State = {
  searchText: string;
  lastAction: string;
  dismissCount: number;
  clearCount: number;
  isLoading: boolean;
  useCustomLoader: boolean;
  showCustomRightElement: boolean;
  showCancelButton: boolean;
  schemeColor: string | null; 
  isInaccessible: boolean;
  useSafeArea: boolean;
  useCustomStyles: boolean;
};

type TestState = {
  testPassed: boolean;
};

export default class SearchInputScreen extends Component<{}, State> {
  state: State = {
    searchText: '',
    lastAction: '',
    dismissCount: 0,
    clearCount: 0,
    isLoading: false,
    useCustomLoader: false,
    showCustomRightElement: false,
    showCancelButton: true,
    schemeColor: null,
    isInaccessible: false,
    useSafeArea: false,
    useCustomStyles: false
  };

    toggleCustomStyles = () => {
    this.setState(prev => ({
      useCustomStyles: !prev.useCustomStyles
    }));
  };

  toggleSafeArea = () => {
    this.setState(prev => ({
      useSafeArea: !prev.useSafeArea
    }));
  };

  onSearchChange = (text: string) => {
    this.setState({searchText: text});
  };

  onClear = () => {
    this.setState(prev => ({
      searchText: '',
      lastAction: 'clear',
      clearCount: prev.clearCount + 1
    }));
  };

  onDismiss = () => {
    Keyboard.dismiss();
    this.setState(prev => ({
      lastAction: 'dismiss',
      dismissCount: prev.dismissCount + 1
    }));
  };

  toggleLoader = () => {
    this.setState(prev => ({
      isLoading: !prev.isLoading
    }));
  };

  renderCustomLoader = () => (
    <View style={{flexDirection: 'row', alignItems: 'center'}}>
      <ActivityIndicator size="small" color="#FF5722"/>
      <Text style={{marginLeft: 8, color: '#FF5722'}}>加载中...</Text>
    </View>
  );

    toggleCustomLoader = () => {
    this.setState(prev => ({
      useCustomLoader: !prev.useCustomLoader
    }));
  };

  renderCustomRightElement = () => (
    <TouchableOpacity 
      onPress={() => Alert.alert('自定义右侧按钮被点击')}
      style={{
        backgroundColor: '#6200EE',
        padding: 8,
        borderRadius: 4,
        marginRight: 8
      }}
    >
      <Text style={{color: 'white'}}>自定义按钮</Text>
    </TouchableOpacity>
  );

  PrimaryButton = () => ({
    title = '点击我',
    disabled = false,
    ...props
  }) => (
    <TouchableOpacity
      disabled={disabled}
      style={[
      ]}
      accessibilityRole="button"
      {...props}
    >
      <Text>
        {title}
      </Text>
    </TouchableOpacity>
  );
  

  toggleCustomRightElement = () => {
    this.setState(prev => ({
      showCustomRightElement: !prev.showCustomRightElement
    }));
  };

   toggleCancelButton = () => {
    this.setState(prev => ({
      showCancelButton: !prev.showCancelButton
    }));
  };
   changeSchemeColor = (color: string | null) => {
    this.setState({ schemeColor: color });
  };

    toggleAccessibility = () => {
    this.setState(prev => ({
      isInaccessible: !prev.isInaccessible
    }), () => {
      // 检查当前无障碍状态
      AccessibilityInfo.isScreenReaderEnabled().then(isEnabled => {
        if (isEnabled) {
          Alert.alert(
            '无障碍提示',
            `搜索框现在处于 ${this.state.isInaccessible ? '不可访问' : '可访问'} 状态`
          );
        }
      });
    });
  };

  onDismiss2 = () => {
    Alert.alert('Cancel was pressed');
  };
  

  render() {
    const {
        searchText,
        lastAction,
        dismissCount,
        clearCount,
        isLoading,
        useCustomLoader,
        showCustomRightElement,
        showCancelButton,
        schemeColor,
        isInaccessible,
        useSafeArea,
        useCustomStyles
    } = this.state;

    const customContainerStyle = {
      backgroundColor: '#f0f8ff',
      borderWidth: 2,
      borderColor: '#1e90ff',
      borderRadius: 20,
      paddingHorizontal: 16,
      marginVertical: 10
    };

    const customInputStyle = {
      color: '#1e90ff',
      fontSize: 18,
      fontWeight: 'bold'
    };

    const customViewStyle = {
      backgroundColor: '#1e90ff',
    };

    return (
      <TestSuite name="SearchInput">
        {/* containerStyle 和 style 属性测试 */}
        <TestCase itShould="自定义输入框样式">
          <View style={{padding: 20}}>
            <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
              <Text>使用自定义样式:</Text>
              <Switch 
                value={useCustomStyles} 
                onValueChange={this.toggleCustomStyles} 
              />
            </View>
            <SearchInput 
              placeholder="输入搜索内容"
              value={searchText}
              onChangeText={this.onSearchChange}
              containerStyle={useCustomStyles ? customContainerStyle : undefined}
            />
            <Text style={{marginTop: 10}}>
              当前样式: {useCustomStyles ? '自定义样式' : '默认样式'}
            </Text>
          </View>
        </TestCase>
        <TestCase itShould="自定义容器样式">
          <View style={{padding: 20}}>
            <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
              <Text>使用自定义样式:</Text>
              <Switch 
                value={useCustomStyles} 
                onValueChange={this.toggleCustomStyles} 
              />
            </View>
            <SearchInput 
              placeholder="输入搜索内容"
              value={searchText}
              onChangeText={this.onSearchChange}
              style={useCustomStyles ? customViewStyle : undefined}
            />
            <Text style={{marginTop: 10}}>
              当前样式: {useCustomStyles ? '自定义样式' : '默认样式'}
            </Text>
          </View>
        </TestCase>
        {/* useSafeArea 属性测试 */}
        <TestCase itShould="安全区域适配">
          <View style={{padding: 20}}>
            <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
              <Text>启用安全区域:</Text>
              <Switch 
                value={useSafeArea} 
                onValueChange={this.toggleSafeArea} 
              />
            </View>
            <SearchInput 
              placeholder={useSafeArea ? "安全区域模式" : "普通模式"}
              value={searchText}
              onChangeText={this.onSearchChange}
              useSafeArea={useSafeArea}
              style={{
                borderWidth: 1,
                borderColor: useSafeArea ? Colors.primary : '#ddd',
                backgroundColor: useSafeArea ? Colors.grey80 : '#fff'
              }}
            />
            <Text style={{marginTop: 10}}>
              当前模式: {useSafeArea ? '安全区域适配' : '普通模式'}
            </Text>
          </View>
        </TestCase>

        {/* inaccessible 属性测试 */}
        <TestCase itShould="控制无障碍访问">
          <View style={{padding: 20}}>
            <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
              <Text>禁用无障碍:</Text>
              <Switch 
                value={isInaccessible} 
                onValueChange={this.toggleAccessibility} 
                accessibilityLabel="切换无障碍状态开关"
              />
            </View>
            <SearchInput 
              placeholder="测试无障碍"
              value={searchText}
              onChangeText={this.onSearchChange}
              inaccessible={isInaccessible}
              accessibilityLabel="搜索输入框"
              accessibilityHint="输入搜索内容"
            />
            <Text style={{marginTop: 10}} accessibilityLiveRegion="polite">
              当前无障碍状态: {isInaccessible ? '禁用' : '启用'}
            </Text>
          </View>
        </TestCase>

        {/* cancelButtonProps 属性测试 */}
        <TestCase itShould="自定义取消按钮属性">
          <View style={{padding: 20}}>
            <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
              <Text>显示取消按钮:</Text>
              <Switch 
                value={showCancelButton} 
                onValueChange={this.toggleCancelButton} 
              />
            </View>
            <SearchInput 
              placeholder="搜索内容..."
              value={searchText}
              onChangeText={this.onSearchChange}
              onDismiss={showCancelButton ? () => Alert.alert('Cancel was pressed') : undefined}
              cancelButtonProps={{label: 'Cancel'}}
            />
          </View>
        </TestCase>

         <TestCase itShould="显示自定义右侧元素">
          <View style={{padding: 20}}>
            <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
              <Text>显示右侧元素:</Text>
              <Switch 
                value={showCustomRightElement} 
                onValueChange={this.toggleCustomRightElement} 
              />
            </View>
            <SearchInput 
              placeholder="搜索内容..."
              value={searchText}
              onChangeText={this.onSearchChange}
              customRightElement={showCustomRightElement ? this.renderCustomRightElement() : undefined}
            />
            <Text style={{marginTop: 10}}>
              当前状态: {showCustomRightElement ? '显示自定义右侧元素' : '默认右侧元素'}
            </Text>
          </View>
        </TestCase>

        {/* 组合测试：自定义加载器和右侧元素 */}
        <TestCase itShould="同时使用自定义加载器和右侧元素">
          <View style={{padding: 20}}>
            <SearchInput 
              placeholder="组合测试"
              showLoader={isLoading}
              customLoader={useCustomLoader ? this.renderCustomLoader() : undefined}
              customRightElement={this.renderCustomRightElement()}
              value={searchText}
              onChangeText={this.onSearchChange}
            />
            <Text style={{marginTop: 10}}>
              组合测试: 自定义加载器{isLoading ? '开启' : '关闭'} + 右侧元素显示中
            </Text>
          </View>
        </TestCase>
        <TestCase itShould="显示自定义加载指示器">
          <View style={{padding: 20}}>
            <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
              <Text>切换加载状态:</Text>
              <Switch 
                value={isLoading} 
                onValueChange={this.toggleLoader} 
              />
            </View>
            <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
              <Text>使用自定义加载器:</Text>
              <Switch 
                value={useCustomLoader} 
                onValueChange={this.toggleCustomLoader} 
              />
            </View>
            <SearchInput 
              placeholder="搜索中..."
              showLoader={isLoading}
              customLoader={useCustomLoader ? this.renderCustomLoader() : undefined}
              value={searchText}
              onChangeText={this.onSearchChange}
            />
            <Text style={{marginTop: 10}}>
              当前状态: {isLoading ? (useCustomLoader ? '自定义加载中...' : '默认加载中...') : '正常模式'}
            </Text>
          </View>
        </TestCase>
        <TestCase itShould="显示加载指示器 (showLoader=true)">
          <View padding-20>
            <View row spread marginB-10>
              <Text text70>切换加载状态:</Text>
              <Switch 
                value={isLoading} 
                onValueChange={this.toggleLoader} 
              />
            </View>
            <SearchInput 
              placeholder="搜索中..."
              showLoader={isLoading}
              value={searchText}
              onChangeText={this.onSearchChange}
            />
            <Text marginT-10>
              当前状态: {isLoading ? '加载中...' : '正常模式'}
            </Text>
          </View>
        </TestCase>

        {/* 带加载状态的完整测试 */}
        <TestCase itShould="加载状态下仍可触发onClear">
          <View padding-20>
            <SearchInput
              showLoader={true}
              value={searchText}
              onChangeText={this.onSearchChange}
              onClear={this.onClear}
            />
            <Text marginT-10>
              清除次数: {clearCount} {lastAction === 'clear' && '(最后一次操作)'}
            </Text>
          </View>
        </TestCase>
        {/* 基础功能测试 */}
        <TestCase itShould="默认SearchInput">
          <View padding-20>
            <SearchInput 
              placeholder="搜索内容..."
              value={searchText}
              onChangeText={this.onSearchChange}
            />
            <Text marginT-10>当前搜索词: {searchText || '(空)'}</Text>
          </View>
        </TestCase>

        {/* 清除功能测试 */}
        <TestCase itShould="触发onClear回调">
          <View padding-20>
            <SearchInput
              value={searchText}
              onChangeText={this.onSearchChange}
              onClear={this.onClear}
            />
            <Text marginT-10>
              清除次数: {clearCount} {lastAction === 'clear' && '(最后一次操作)'}
            </Text>
          </View>
        </TestCase>

        {/* 取消功能测试 */}
        <TestCase itShould="触发onDismiss回调">
          <View padding-20>
            <SearchInput
              value={searchText}
              onChangeText={this.onSearchChange}
              onDismiss={this.onDismiss}
              cancelButtonProps={{label: 'Cancel'}}
            />
            <Text marginT-10>
              取消次数: {dismissCount} {lastAction === 'dismiss' && '(最后一次操作)'}
            </Text>
          </View>
        </TestCase>

        {/* 组合功能测试 */}
        <TestCase
          itShould="同时测试onClear和onDismiss"
          initialState={{testPassed: false} as TestState}
          arrange={({setState}) => (
            <View padding-20>
              <SearchInput
                value={searchText}
                onChangeText={this.onSearchChange}
                onClear={() => {
                  this.onClear();
                  setState({testPassed: true});
                }}
                onDismiss={this.onDismiss}
              />
              <View marginT-10>
                <Text>搜索状态: {searchText || '(空)'}</Text>
                <Text>清除次数: {clearCount}</Text>
                <Text>取消次数: {dismissCount}</Text>
              </View>
            </View>
          )}
          assert={({state, expect}) => {
            expect(state.testPassed).to.be.true;
          }}
        />

      </TestSuite>
    );
  }
}